package org.x.usermod.service.impl;

import ch.qos.logback.core.util.StringUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.idev.excel.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.x.commonmod.pojo.PubSysUser;
import org.x.commonmod.config.Result;
import org.x.usermod.dto.*;
import org.x.usermod.entity.*;
import org.x.usermod.mapper.*;
import org.x.usermod.service.ISysRoleUserService;
import org.x.usermod.service.ISysUserService;
import org.x.commonmod.config.BusinessException;
import org.x.usermod.vo.LoginVO;
import com.mybatisflex.core.paginate.Page;
import org.x.usermod.vo.SysUserVO;
import org.x.usermod.vo.UserInfoVO;
import org.x.usermod.dto.UpdateProfileDTO;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysRoleUserService sysRoleUserService;
    @Autowired
    private CodeMapper codeMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysUserRealnameAuthMapper sysUserRealnameAuthMapper;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result createUserWithValidation(CreateUserDTO createUserDTO) {
        // 1. 参数校验
        if (createUserDTO.getUsername() == null || createUserDTO.getUsername().isEmpty()) {
            return Result.fail("400", "用户名不能为空");
        }
        if (createUserDTO.getPassword() == null || createUserDTO.getPassword().isEmpty()) {
            return Result.fail("400", "密码不能为空");
        }
        if (createUserDTO.getPassword().length() < 6 || createUserDTO.getPassword().length() > 20) {
            return Result.fail("400", "密码长度必须在6到20之间");
        }
        if (createUserDTO.getMobile() == null || createUserDTO.getMobile().isEmpty()) {
            return Result.fail("400", "手机号不能为空");
        }
        if (createUserDTO.getRoleId() == null && createUserDTO.getUserType() == null) {
            return Result.fail("400", "必须指定角色ID或用户类型");
        }

        // 2. 检查用户名和手机号是否已存在
        try {
            if (isUsernameExists(createUserDTO.getUsername())) {
                return Result.fail("400", "用户名已存在");
            }
            if (isPhoneExists(createUserDTO.getMobile())) {
                return Result.fail("400", "手机号已存在");
            }

            // 3. 调用内部方法创建用户
            int result = createUser(createUserDTO);

            // 4. 返回创建结果
            if (result > 0) {
                return Result.ok("用户创建成功");
            }
            return Result.fail("500", "用户创建失败");
        } catch (BusinessException e) {
            throw e;
        }catch (Exception e) {
            log.error("创建用户失败", e);
            throw new BusinessException("创建用户失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int createUser(CreateUserDTO createUserDTO) throws BusinessException {
        try {
            // 1. 密码加密
            String encryptPassword = sha256(createUserDTO.getPassword());
            createUserDTO.setPassword(encryptPassword);

            // 2. DTO转SysUser
            SysUser userEntity = new SysUser();
            BeanUtils.copyProperties(createUserDTO, userEntity);

            // 3. 设置默认值
            userEntity.setStatus(1);
            userEntity.setIsDelete(0);
            userEntity.setCreatedTime(convertToDate(LocalDateTime.now()));
            userEntity.setUpdatedTime(convertToDate(LocalDateTime.now()));

            // 4. 保存用户
            int result = sysUserMapper.insert(userEntity);
            if (result <= 0) {
                throw new BusinessException("用户创建失败");
            }

            // 5. 处理角色关联
            Long roleId = createUserDTO.getRoleId() != null ?
                    createUserDTO.getRoleId() : determineRoleIdByUserType(createUserDTO.getUserType());

            if (roleId != null) {
                createUserRole(userEntity.getId(), roleId); // 这个方法应该抛出异常
            }

            return result;
        } catch (Exception e) {
            log.error("创建用户失败", e);
            throw new BusinessException("创建用户失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Result updateUserWithValidation(UpdateUserDTO updateUserDTO) throws BusinessException {
        // 1. 参数校验
        if (updateUserDTO.getId() == null) {
            return Result.fail("400", "用户ID不能为空");
        }

        // 2. 检查用户是否存在
        SysUser existingUser = sysUserMapper.selectOneById(updateUserDTO.getId());
        if (existingUser == null || existingUser.getIsDelete() == 1) {
            return Result.fail("404", "用户不存在或已被删除");
        }

        // 3. 检查手机号是否已被其他用户使用
        if (updateUserDTO.getMobile() != null && !updateUserDTO.getMobile().equals(existingUser.getMobile())) {
            if (isPhoneExists(updateUserDTO.getMobile())) {
                return Result.fail("400", "手机号已被其他用户使用");
            }
        }

        // 4. 调用内部方法更新用户
        int result = updateUser(updateUserDTO);
        if (result > 0) {
            return Result.ok("用户更新成功");
        }
        return Result.fail("500", "用户更新失败");
    }

    /**更新用户信息
     * @param updateUserDTO
     * @return
     */
    @Override
    @Transactional
    public int updateUser(UpdateUserDTO updateUserDTO) {
        //检验用户是否存在
        SysUser user = sysUserMapper.selectOneById(updateUserDTO.getId());
        if (user != null)
        {
            //检验部门有效性
            if (updateUserDTO.getDeptId() != null)
            {
                //更新用户信息
                BeanUtils.copyProperties(updateUserDTO, user);
                //判断是否传输密码
                if (updateUserDTO.getPassword() != null && !updateUserDTO.getPassword().isEmpty())
                {
                    user.setPassword(sha256(updateUserDTO.getPassword()));
                }
                sysUserMapper.insertOrUpdateSelective( user);
                //删除旧的角色关联
                sysRoleUserMapper.deleteByQuery(new QueryWrapper().eq("user_id", updateUserDTO.getId()));
                //跟新角色关联
                List<SysRoleUser> roleUsers = new ArrayList<>();
                for (long roleId : updateUserDTO.getRoleIds())
                {
                    SysRoleUser roleUser = new SysRoleUser();
                    roleUser.setUserId(updateUserDTO.getId());
                    roleUser.setRoleId(roleId);
                    roleUsers.add(roleUser);

                }
                return sysRoleUserMapper.insertBatch(roleUsers);
            }
        }
        return 0;
    }

    // 辅助方法
    private void updateUserFields(SysUser user, UpdateUserDTO dto) throws BusinessException {
        if (dto.getPassword() != null && !dto.getPassword().isEmpty()) {
            user.setPassword(sha256(dto.getPassword()));
        }
        if (dto.getEmail() != null) {
            user.setEmail(dto.getEmail());
        }
        if (dto.getMobile() != null) {
            user.setMobile(dto.getMobile());
        }
        if (dto.getDeptId() != null) {
            user.setDeptId(dto.getDeptId());
        }
        if (dto.getUserType() != null) {
            user.setUserType(dto.getUserType());
        }
        if (dto.getStatus() != null) {
            user.setStatus(dto.getStatus());
        }
        if (dto.getUpdatedBy() != null) {
            user.setUpdatedBy(dto.getUpdatedBy());
        }
    }
//    @TOOD
    private void updateUserRole(Long userId, Long roleId) {
        // 删除旧角色关联
        int deleteResult = sysRoleUserService.removeByUserId(userId);
        log.debug("删除用户{}的角色关联，影响行数: {}", userId, deleteResult);

        // 添加新角色关联
        SysRoleUser roleUser = new SysRoleUser();
        roleUser.setUserId(userId);
        roleUser.setRoleId(roleId);
        roleUser.setCreatedTime(convertToDate(LocalDateTime.now()));

        sysRoleUserService.save(roleUser);
    }

    private void createUserRole(Long userId, Long roleId) {
        try {
            SysRoleUser roleUser = new SysRoleUser();
            roleUser.setUserId(userId);
            roleUser.setRoleId(roleId);
            roleUser.setCreatedTime(convertToDate(LocalDateTime.now()));
            sysRoleUserService.save(roleUser);
        } catch (Exception e) {
            log.error("创建用户角色关联失败", e);
            throw new BusinessException("创建用户角色关联失败");
        }
    }

    private Long determineRoleIdByUserType(String userType) {
        if ("ADMIN".equals(userType)) {
            return 1L;
        } else if ("LAWYER".equals(userType)) {
            return 2L;
        } else if ("USER".equals(userType)) {
            return 3L;
        }
        return null;
    }

    private Date convertToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
    }

    private String sha256(String input) throws BusinessException {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(input.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new BusinessException("密码加密失败");
        }
    }

    @Override
    public boolean isUsernameExists(@NotBlank(message = "用户名不能为空") String username) {
        return sysUserMapper.selectCountByQuery(
                QueryWrapper.create()
                        .where(SysUser::getUsername).eq(username)
                        .and(SysUser::getIsDelete).eq(0)
        ) > 0;
    }

    @Override
    public boolean isPhoneExists(@NotBlank(message = "手机号不能为空") String mobile) {
        return sysUserMapper.selectCountByQuery(
                QueryWrapper.create()
                        .where(SysUser::getMobile).eq(mobile)
                        .and(SysUser::getIsDelete).eq(0)
        ) > 0;
    }

    @Override
    public LoginVO login(LoginDTO loginDTO) throws BusinessException {

//        String password = "xhl123";
//        password = sha256(password);
//        System.out.println(password);

        QueryWrapper wapper = new QueryWrapper();
        wapper.eq("username", loginDTO.getUsername());

        SysUser sysUser = sysUserMapper.selectOneByQuery(wapper);
        if (sysUser == null) {
            throw new BusinessException("用户名不存在");
        }
        if (!sysUser.getPassword().equals(sha256(loginDTO.getPassword()))) {
            throw new BusinessException("密码错误");
        }
        if (sysUser.getStatus() == 0) {
            throw new BusinessException("用户已禁用");
        }
        if (sysUser.getIsDelete() == 1) {
            throw new BusinessException("用户已删除");
        }

        PubSysUser user = new PubSysUser();
        user.setUsername(sysUser.getUsername());
        user.setUserType(sysUser.getUserType());
        user.setUserId(String.valueOf(sysUser.getId()));

        StpUtil.login(sysUser.getId());
        StpUtil.getSession().set("user", user);

        LoginVO loginVO = new LoginVO();
        loginVO.setUserEntity(sysUser);
        loginVO.setToken(StpUtil.getTokenValue());

        return loginVO;
    }

    /* *
     * 逻辑删除用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result removeById(Long id) {
        try {
            // 逻辑删除，设置is_delete=1
            SysUser user = sysUserMapper.selectOneById(id);
            if (user == null) {
                return Result.fail("404", "用户不存在");
            }

            user.setIsDelete(1);
            user.setUpdatedTime(convertToDate(LocalDateTime.now()));
            int result = sysUserMapper.update(user);

            if (result > 0) {
                log.info("用户假删除成功，用户ID: {}", id);
                return Result.ok("用户删除成功");
            }
            return Result.fail("500", "用户删除失败");
        } catch (Exception e) {
            log.error("删除用户失败", e);
            throw new BusinessException("删除用户失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result restoreById(Long id) {
        try {
            // 逻辑，设置is_delete=0
            SysUser user = sysUserMapper.selectOneById(id);
            if (user == null) {
                return Result.fail("404", "用户不存在");
            }

            user.setIsDelete(0);
            user.setUpdatedTime(convertToDate(LocalDateTime.now()));
            int result = sysUserMapper.update(user);

            if (result > 0) {
                log.info("用户恢复成功，用户ID: {}", id);
                return Result.ok("用户恢复成功");
            }
            return Result.fail("500", "用户恢复失败");
        } catch (Exception e) {
            log.error("恢复用户失败", e);
            throw new BusinessException("恢复用户失败: " + e.getMessage());
        }
    }
    @Override
    public Result getById(Long id) {
        try {
            SysUser user = sysUserMapper.selectOneById(id);
            if (user == null || user.getIsDelete() == 1) {
                return Result.ok("用户不存在或已被删除");
            }
            return Result.ok(user);
        } catch (Exception e) {
            return Result.fail("500", "查询用户失败");
        }
    }

    @Override
    public Page<SysUserVO> List(ListDto listDto) {
        //检验ListDto参数使否为空，不为空才构建查询条件
        QueryWrapper wrapper = new QueryWrapper();
        if(!StringUtil.isNullOrEmpty(listDto.getUsername()))
        {
            wrapper.like(SysUser::getUsername, listDto.getUsername());
        }
         if(!StringUtil.isNullOrEmpty(listDto.getMobile()))
        {
            wrapper.like(SysUser::getMobile, listDto.getMobile());
        }
         if(!StringUtil.isNullOrEmpty(listDto.getEmail()))
        {
            wrapper.like(SysUser::getEmail, listDto.getEmail());
        }
         if(!StringUtil.isNullOrEmpty(listDto.getUserType()))
        {
            wrapper.like(SysUser::getUserType, listDto.getUserType());
        }
         if(!StringUtil.isNullOrEmpty(String.valueOf(listDto.getStatus())))
        {
            wrapper.like(SysUser::getStatus, listDto.getStatus());
        }
         if(!StringUtil.isNullOrEmpty(String.valueOf(listDto.getDeptId())))
        {
            wrapper.like(SysUser::getDeptId, listDto.getDeptId());
        }
        Page<SysUser> page = sysUserMapper.paginate(
                listDto.getPage(),
                listDto.getSize(),
                wrapper
        );
        //paginate方法返回的是Page<T>，需要转换成Page<SysUserVo>
        Page<SysUserVO> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        return pageVo;

    }



    @Override
    public Result resetPassword(@Valid ResetPasswordDTO resetPasswordDTO) {
        try {
            SysUser user = sysUserMapper.selectOneById(resetPasswordDTO.getUserId());
            if (user == null) {
                return Result.fail("404", "用户不存在");
            }
            if (!user.getPassword().equals(sha256(resetPasswordDTO.getPassword()))) {
                return Result.fail("400", "旧密码错误");
            }
            if (!resetPasswordDTO.getNewPassword().equals(resetPasswordDTO.getConfirmPassword())) {
                return Result.fail("400", "两次密码不一致");
            }
            user.setPassword(sha256(resetPasswordDTO.getNewPassword()));
            user.setUpdatedTime(convertToDate(LocalDateTime.now()));
            int result = sysUserMapper.update(user);
            if (result > 0) {
                return Result.ok("密码重置成功");
            }
            return Result.fail("500", "密码重置失败");
        } catch (Exception e) {
            log.error("密码重置失败", e);
            throw new BusinessException("密码重置失败: " + e.getMessage());
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result resetMobile(@Valid ResetMobileDTO resetMobileDTO) {
        try {
            SysUser user = sysUserMapper.selectOneById(resetMobileDTO.getUserId());
            if (user == null) {
                return Result.fail("404", "用户不存在");
            }
            if (!user.getMobile().equals(resetMobileDTO.getOldMobile())) {
                return Result.fail("400", "旧手机号错误");
            }
            if (user.getMobile().equals(resetMobileDTO.getNewMobile())) {
                return Result.fail("400", "新手机号不能与旧手机号相同");
            }
            // 验证验证码 (这里需要接入短信验证服务)
            //@TOOD
//            if (!smsService.verifyCode(resetMobileDTO.getNewMobile(), resetMobileDTO.getCode(), "CHANGE_MOBILE")) {
//                return Result.fail("600", "验证码错误或已过期");
//            }
            //假设验证码为123
            if (!resetMobileDTO.getCode().equals("123")) {
                return Result.fail("600", "验证码错误或已过期");
            }
            if (isPhoneExists(resetMobileDTO.getNewMobile())) {
                return Result.fail("400", "新手机号已被其他用户使用");
            }
            user.setMobile(resetMobileDTO.getNewMobile());
            user.setUpdatedTime(convertToDate(LocalDateTime.now()));
            int result = sysUserMapper.update(user);
            if (result > 0) {
                return Result.ok("手机号重置成功");
            }
            return Result.fail("500", "手机号重置失败");
        } catch (Exception e) {
            log.error("手机号重置失败", e);
            throw new BusinessException("手机号重置失败: " + e.getMessage());
        }
    }
    // 获取SysUserRealnameAuth信息
    @Override
    public SysUserRealnameAuth getSysUserRealnameAuth(@Valid Long userId) {
        // 创建正确的查询条件，指定查询userId字段
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(SysUserRealnameAuth::getUserId).eq(userId)
                .orderBy(SysUserRealnameAuth::getCreatedAt, false) // 按创建时间降序
                .limit(1); // 只取最新的一条记录

        // 使用正确的查询方法
        SysUserRealnameAuth sysUserRealnameAuth = sysUserRealnameAuthMapper.selectOneByQuery(queryWrapper);

        return sysUserRealnameAuth; // 可能为null
    }
    //提交实名认证
    @Override
    public Result submitRealnameAuth(@Valid SURrealnamAuthDTO sysUserRealnameAuthDTO,Long userId) {
        //根据userId检查是否存在申请记录，如果存在则更新，不存在则插入
        SysUserRealnameAuth sysUserRealnameAuth = getSysUserRealnameAuth(userId);
        if(sysUserRealnameAuth!=null)
        {
            //更新
            sysUserRealnameAuth.setRealName(sysUserRealnameAuthDTO.getRealName());
            sysUserRealnameAuth.setIdCard(sysUserRealnameAuthDTO.getIdCard());
            sysUserRealnameAuth.setAuthStatus(1);
            sysUserRealnameAuth.setUserId(StpUtil.getLoginIdAsLong());
            sysUserRealnameAuth.setUpdatedAt(new java.sql.Date(System.currentTimeMillis()));
            sysUserRealnameAuthMapper.update(sysUserRealnameAuth);
            return Result.ok();
        }
        else
        {
            //插入
            sysUserRealnameAuth = new SysUserRealnameAuth();
            BeanUtils.copyProperties(sysUserRealnameAuthDTO, sysUserRealnameAuth);
            sysUserRealnameAuth.setAuthStatus(1);
            sysUserRealnameAuth.setUserId(StpUtil.getLoginIdAsLong());
            sysUserRealnameAuth.setCreatedAt(new java.sql.Date(System.currentTimeMillis()));
            sysUserRealnameAuth.setUpdatedAt(new java.sql.Date(System.currentTimeMillis()));
            sysUserRealnameAuthMapper.insert(sysUserRealnameAuth);
            return Result.ok();
        }

    }

    //分页获取待审核的实名认证信息列表
    @Override
    public Result getAuthPendingList(RealnameAuthPageDTO realnameAuthPageDTO) {
        try {
            // 1. 参数校验
            if (realnameAuthPageDTO == null) {
                return Result.fail("400", "参数不能为空");
            }
            if (realnameAuthPageDTO.getPageNum() == null || realnameAuthPageDTO.getPageNum() <= 0) {
                realnameAuthPageDTO.setPageNum(1); // 默认第一页
            }
            if (realnameAuthPageDTO.getPageSize() == null || realnameAuthPageDTO.getPageSize() <= 0) {
                realnameAuthPageDTO.setPageSize(10); // 默认每页10条
            }

            // 2. 构建查询条件
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .where(SysUserRealnameAuth::getAuthStatus).eq(1) // 只查询待审核状态(1)的记录
                    .orderBy(SysUserRealnameAuth::getCreatedAt, false); // 按创建时间降序

            // 3. 添加可选查询条件
            if (realnameAuthPageDTO.getUserId() != null) {
                queryWrapper.and(SysUserRealnameAuth::getUserId).eq(realnameAuthPageDTO.getUserId());
            }
            if (realnameAuthPageDTO.getRealName() != null && !realnameAuthPageDTO.getRealName().isEmpty()) {
                queryWrapper.and(SysUserRealnameAuth::getRealName).like(realnameAuthPageDTO.getRealName());
            }
            if (realnameAuthPageDTO.getIdCard() != null && !realnameAuthPageDTO.getIdCard().isEmpty()) {
                queryWrapper.and(SysUserRealnameAuth::getIdCard).like(realnameAuthPageDTO.getIdCard());
            }

            // 4. 执行分页查询
            Page<SysUserRealnameAuth> page = sysUserRealnameAuthMapper.paginate(
                    realnameAuthPageDTO.getPageNum(),
                    realnameAuthPageDTO.getPageSize(),
                    queryWrapper
            );

            // 5. 返回结果
            return Result.ok(page);
        } catch (Exception e) {
            log.error("获取待审核实名认证列表失败", e);
            return Result.fail("500", "获取待审核实名认证列表失败: " + e.getMessage());
        }
    }
    //审核用户的实名认证申请
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result verifyRealnameAuth(@Valid AuthVerifyDTO authVerifyDTO) {
        // 参数校验
        if (authVerifyDTO == null || authVerifyDTO.getUserId() == null) {
            return Result.fail("400", "参数错误");
        }

        // 查询用户实名认证信息
        SysUserRealnameAuth sysUserRealnameAuth = sysUserRealnameAuthMapper.selectOneByQuery(QueryWrapper.create().eq(SysUserRealnameAuth::getUserId, authVerifyDTO.getUserId()));
        if (sysUserRealnameAuth == null) {
            return Result.fail("404", "用户实名认证信息不存在");
        }

        // 状态校验
        Integer authStatus = authVerifyDTO.getAuthStatus();
        if (authStatus == null || (authStatus != 2 && authStatus != 3)) {
            return Result.fail("400", "认证状态参数错误");
        }

        // 如果是拒绝状态(3)，必须提供拒绝原因
        if (authStatus == 3 && StringUtils.isBlank(authVerifyDTO.getRejectReason())) {
            return Result.fail("400", "拒绝原因不能为空");
        }

        // 更新认证信息
        sysUserRealnameAuth.setAuthStatus(authStatus);
        sysUserRealnameAuth.setRejectReason(authStatus == 3 ? authVerifyDTO.getRejectReason() : null);
        sysUserRealnameAuth.setVerifiedAt(new java.sql.Date(System.currentTimeMillis()));

        // 执行更新
        int updateCount = sysUserRealnameAuthMapper.update(sysUserRealnameAuth);
        if (updateCount <= 0) {
            return Result.fail("500", "更新实名认证状态失败");
        }

        return Result.ok();
    }
    @Override
    public UserInfoVO getUserAuthInfo() {
        UserInfoVO userInfoVO = new UserInfoVO();

        // 0. 查询用户信息
        SysUser sysUser = sysUserMapper.selectOneById(StpUtil.getLoginIdAsLong());
        userInfoVO.setId(sysUser.getId());
        userInfoVO.setUserName(sysUser.getUsername());
        userInfoVO.setRealName(sysUser.getRealName());
        userInfoVO.setDeptId(sysUser.getDeptId());

        // 1. 查询权限
        List<CodeDTO> code = codeMapper.getCode();
        List<String> permissions = code.stream()
                .map(CodeDTO::getCode)
                .collect(Collectors.toList());
        userInfoVO.setPermissions(permissions);

        // 2. 查询角色
        QueryWrapper roleUserQueryWrapper = new QueryWrapper();
        roleUserQueryWrapper.eq(SysRoleUser::getUserId, StpUtil.getLoginIdAsLong());
        List<SysRoleUser> sysRoleUserEntities = sysRoleUserMapper.selectListByQuery(roleUserQueryWrapper);

        List<Long> roleIds = sysRoleUserEntities.stream()
                .map(SysRoleUser::getRoleId)
                .collect(Collectors.toList());

        List<SysRole> sysRoleEntities = CollectionUtils.isEmpty(roleIds) ?
                Collections.emptyList() :
                sysRoleMapper.selectListByIds(roleIds);
        List<String> roleNames = sysRoleEntities.stream()
                .map(SysRole::getName)
                .collect(Collectors.toList());
        userInfoVO.setRoles(roleNames);

        // 3. 查询菜单
        Set<Long> aclSet = code.stream()
                .map(CodeDTO::getAclId)
                .collect(Collectors.toSet());

        QueryWrapper menuQueryWrapper = new QueryWrapper();
        if (!CollectionUtils.isEmpty(aclSet)) {
            menuQueryWrapper.in(SysMenu::getAclId, aclSet)
                    .or(SysMenu::getAclId).isNull();
        } else {
            menuQueryWrapper.where(SysMenu::getAclId).isNull();
        }

        List<SysMenu> sysMenuEntities = sysMenuMapper.selectListByQuery(menuQueryWrapper);

        // 4. 构建菜单树
        List<UserInfoVO.MenuTreeVO> menuTreeVOS = this.buildTree(sysMenuEntities);
        userInfoVO.setMenuTree(menuTreeVOS);

        return userInfoVO;
    }


    // 构建菜单树的方法
    public List<UserInfoVO.MenuTreeVO> buildTree(List<SysMenu> menus) {
        // 1. 获取所有根节点（parentId为0或null的菜单）
        List<UserInfoVO.MenuTreeVO> roots = menus.stream()
                .filter(menu -> menu.getParentId() == null || 0 == menu.getParentId())
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 2. 递归构建子节点
        roots.forEach(root -> findChildren(root, menus));

        return roots;
    }

    private void findChildren(UserInfoVO.MenuTreeVO parent, List<SysMenu> allMenus) {
        List<UserInfoVO.MenuTreeVO> children = allMenus.stream()
                .filter(menu -> parent.getId().equals(menu.getParentId()))
                .map(this::convertToVO)
                .collect(Collectors.toList());

        parent.setChildren(children);
        children.forEach(child -> findChildren(child, allMenus)); // 递归处理子节点
    }

    private UserInfoVO.MenuTreeVO convertToVO(SysMenu entity) {
        UserInfoVO.MenuTreeVO vo = new UserInfoVO.MenuTreeVO();
        vo.setId(entity.getId());
        vo.setName(entity.getName());
        vo.setPath(entity.getPath());
        vo.setIcon(entity.getIcon());
        vo.setComponent(entity.getPath());
        vo.setRequiresAuth(true);
        // 其他字段拷贝...
        JSONObject meta = new JSONObject();
        meta.put("title", entity.getName());
        meta.put("icon", entity.getIcon());
        meta.put("requiresAuth", true);
        vo.setMeta(meta);

        return vo;
    }

    @Override
    public PersonalInfoDTO getProfile() {
        //获取当前登录用户信息
        PersonalInfoDTO personalInfoDTO = new PersonalInfoDTO();
        // 1. 查询用户信息
        SysUser sysUser = sysUserMapper.selectOneById(StpUtil.getLoginIdAsLong());
        personalInfoDTO.setUserId(sysUser.getId());
        personalInfoDTO.setUsername(sysUser.getUsername());
        personalInfoDTO.setRealName(sysUser.getRealName());
        personalInfoDTO.setMobile(sysUser.getMobile());
        personalInfoDTO.setEmail(sysUser.getEmail());
        personalInfoDTO.setAuthStatus(sysUser.getStatus());
        personalInfoDTO.setUserType(sysUser.getUserType());
        return personalInfoDTO;
    }
    //修改用户信息
    @Override
    public Result updateProfile(UpdateProfileDTO updateProfileDTO) {
        // 1. 获取当前用户
        Long userId = StpUtil.getLoginIdAsLong();
        SysUser sysUser = sysUserMapper.selectOneById(userId);
        if (sysUser == null) {
            return Result.fail("400", "用户不存在");
        }

        // 2. 检查用户名是否被其他用户使用（排除自己）
        if (StringUtils.isNotBlank(updateProfileDTO.getUsername())) {
            QueryWrapper usernameQuery = QueryWrapper.create()
                    .eq(SysUser::getUsername, updateProfileDTO.getUsername())
                    .ne(SysUser::getId, userId); // 排除当前用户
            if (sysUserMapper.selectOneByQuery(usernameQuery) != null) {
                return Result.fail("400", "用户名已存在");
            }
        }

        // 3. 检查邮箱是否被其他用户使用（排除自己）
        if (StringUtils.isNotBlank(updateProfileDTO.getEmail())) {
            QueryWrapper emailQuery = QueryWrapper.create()
                    .eq(SysUser::getEmail, updateProfileDTO.getEmail())
                    .ne(SysUser::getId, userId); // 排除当前用户
            if (sysUserMapper.selectOneByQuery(emailQuery) != null) {
                return Result.fail("400", "邮箱已存在");
            }
        }

        // 4. 更新用户信息
        if (StringUtils.isNotBlank(updateProfileDTO.getUsername())) {
            sysUser.setUsername(updateProfileDTO.getUsername());
        }
        if (StringUtils.isNotBlank(updateProfileDTO.getEmail())) {
            sysUser.setEmail(updateProfileDTO.getEmail());
        }
        sysUser.setUpdatedBy(StpUtil.getLoginIdAsString()); // 使用用户ID而非用户名作为更新人
        sysUser.setUpdatedTime(new Timestamp(System.currentTimeMillis())); // 使用Timestamp更精确

        // 5. 执行更新
        sysUserMapper.update(sysUser);

        return Result.ok();
    }
}